<template>
  <div class="inspection-form-container">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <!-- 新建按钮（权限控制） -->
      <el-button 
        type="primary" 
        @click="openCreateDialog"
        v-if="hasPermission('Add')"
        :loading="operationLoading"
      >
        <i class="el-icon-plus"></i> 新建
      </el-button>
      
      <!-- 导出按钮（权限控制） -->
      <el-button 
        type="info" 
        @click="showInspectorSelectDialog"
        v-if="hasPermission('Export')"
        style="margin-left: 10px"
        :loading="operationLoading"
      >
        <i class="el-icon-download"></i> 导出Excel
      </el-button>
      
      <!-- 搜索区域 -->
      <el-input
        v-model="searchKeyword"
        placeholder="请输入查询内容（工单号、产品代码、检验员等）"
        clearable
        style="width: 300px; margin-left: 20px"
        @keyup.enter="handleSearch"
      ></el-input>
      
      <el-button 
        type="success" 
        @click="handleSearch" 
        style="margin-left: 10px"
        :loading="searchLoading"
      >
        <i class="el-icon-search"></i> 查询
      </el-button>
      
      <!-- 刷新按钮 -->
      <el-button 
        type="default" 
        @click="refreshData" 
        style="margin-left: 10px"
        :loading="operationLoading"
      >
        <i class="el-icon-refresh"></i> 刷新
      </el-button>
      
      <!-- 权限状态提示 -->
      <div class="permission-info" v-if="showPermissionInfo">
        当前权限: 
        <span :class="{ 'permission-enabled': hasPermission('Add') }">新建</span> |
        <span :class="{ 'permission-enabled': hasPermission('Update') }">编辑</span> |
        <span :class="{ 'permission-enabled': hasPermission('Delete') }">删除</span> |
        <span :class="{ 'permission-enabled': hasPermission('Export') }">导出</span>
      </div>
    </div>

    <!-- 表格展示 -->
    <el-table
      :data="filteredData"
      border
      stripe
      style="width: 100%; margin-top: 20px"
      v-loading="tableLoading"
      element-loading-text="加载中..."
    >
      <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
      <el-table-column label="工单号" prop="workOrderNo" align="center"></el-table-column>
      <el-table-column label="产品代码" prop="productCode" align="center"></el-table-column>
      <el-table-column label="批次号" prop="batchNo" align="center"></el-table-column>
      <el-table-column label="时间段" align="center">
        <template #default="scope">
          {{ scope.row.startTime }} - {{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column label="检验员" align="center">
        <template #default="scope">
          {{ scope.row.inspectors.join('、') }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-tag :type="statusTagType[scope.row.status] || 'default'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" align="center"></el-table-column>
      <el-table-column prop="totalTime" label="总时长(小时)" align="center"></el-table-column>
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <!-- 编辑按钮（权限控制） -->
          <el-button
            type="warning"
            size="mini"
            @click="openEditDialog(scope.row)"
            v-if="hasPermission('Update')"
            :loading="operationLoading"
          >
            <i class="el-icon-edit"></i> 编辑
          </el-button>
          
          <!-- 删除按钮（权限控制） -->
          <el-button
            type="danger"
            size="mini"
            @click="handleDelete(scope.row.id)"
            style="margin-left: 5px"
            v-if="hasPermission('Delete')"
            :loading="operationLoading"
          >
            <i class="el-icon-delete"></i> 删除
          </el-button>
          
          <!-- 无权限时显示占位符 -->
          <span v-if="!hasPermission('Update') && !hasPermission('Delete')">-</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="90%"
      :before-close="handleDialogClose"
      ref="dialogRef"
    >
      <div class="dialog-content">
        <!-- 上部分：基本信息 -->
        <div class="dialog-section">
          <h3 class="section-title">基本信息</h3>
          <!-- 第一行基本信息：工单号、产品代码、批次号、产品规格、牌号、镀层 -->
          <div class="form-group">
            <!-- 工单号 -->
            <div class="form-item">
              <label class="form-label">工单号</label>
              <el-input
                v-model="baseInfo.workOrderNo"
                placeholder="请输入工单号"
                @keyup.enter="handleWorkOrderEnter"
                :disabled="currentEditId !== null"
              ></el-input>
            </div>
            <!-- 产品代码 -->
            <div class="form-item">
              <label class="form-label">产品代码</label>
              <el-input
                v-model="baseInfo.productCode"
                placeholder="请输入产品代码"
              ></el-input>
            </div>
            <!-- 批次号 -->
            <div class="form-item">
              <label class="form-label">批次号</label>
              <el-input
                v-model="baseInfo.batchNo"
                placeholder="请输入批次号"
              ></el-input>
            </div>
            <!-- 产品规格 -->
            <div class="form-item">
              <label class="form-label">产品规格</label>
              <el-input
                v-model="baseInfo.productSpec"
                placeholder="请输入产品规格"
              ></el-input>
            </div>
            <!-- 牌号 -->
            <div class="form-item">
              <label class="form-label">牌号</label>
              <el-input
                v-model="baseInfo.grade"
                placeholder="请输入牌号"
              ></el-input>
            </div>
            <!-- 镀层 -->
            <div class="form-item">
              <label class="form-label">镀层</label>
              <el-input
                v-model="baseInfo.coating"
                placeholder="请输入镀层"
              ></el-input>
            </div>
          </div>
          
          <!-- 第二行基本信息：单重、批次数量、合格数量、批次重量、包材总重 -->
          <div class="form-group">
            <!-- 单重 -->
            <div class="form-item">
              <label class="form-label">单重</label>
              <el-input
                v-model.number="baseInfo.unitWeight"
                type="number"
                placeholder="请输入单重"
                min="0"
                step="0.01"
              ></el-input>
            </div>
            <!-- 批次数量 -->
            <div class="form-item">
              <label class="form-label">批次数量</label>
              <el-input
                v-model.number="baseInfo.batchQuantity"
                type="number"
                placeholder="请输入批次数量"
                min="0"
              ></el-input>
            </div>
            <!-- 合格数量 -->
            <div class="form-item">
              <label class="form-label">合格数量</label>
              <el-input
                v-model.number="baseInfo.qualifiedQuantity"
                type="number"
                placeholder="请输入合格数量"
                min="0"
              ></el-input>
            </div>
            <!-- 批次重量 -->
            <div class="form-item">
              <label class="form-label">批次重量</label>
              <el-input
                v-model.number="baseInfo.batchWeight"
                type="number"
                placeholder="请输入批次重量"
                min="0"
                step="0.01"
              ></el-input>
            </div>
            <!-- 包材总重 -->
            <div class="form-item">
              <label class="form-label">包材总重</label>
              <el-input
                v-model.number="baseInfo.packagingWeight"
                type="number"
                placeholder="请输入包材总重"
                min="0"
                step="0.01"
              ></el-input>
            </div>
          </div>
        </div>
        
        <!-- 下部分：检验记录 -->
        <div class="dialog-section">
          <h3 class="section-title">检验记录</h3>
          <div
            v-for="(row, index) in formRows"
            :key="index"
            class="form-row"
          >
            <!-- 开始日期 -->
            <div class="form-item form-item-time">
              <label class="form-label">开始日期</label>
              <el-date-picker
                v-model="row.startDate"
                type="date"
                placeholder="选择开始日期"
                :clearable="false"
                @change="calculateTimeDiff(row)"
              ></el-date-picker>
            </div>
            
            <!-- 开始时间 -->
            <div class="form-item form-item-time">
              <label class="form-label">开始时间</label>
              <el-time-picker
                v-model="row.startTime"
                placeholder="选择开始时间"
                :clearable="false"
                @change="calculateTimeDiff(row)"
              ></el-time-picker>
            </div>
            
            <!-- 结束日期 -->
            <div class="form-item form-item-time">
              <label class="form-label">结束日期</label>
              <el-date-picker
                v-model="row.endDate"
                type="date"
                placeholder="选择结束日期"
                :clearable="false"
                @change="calculateTimeDiff(row)"
              ></el-date-picker>
            </div>
            
            <!-- 结束时间 -->
            <div class="form-item form-item-time">
              <label class="form-label">结束时间</label>
              <el-time-picker
                v-model="row.endTime"
                placeholder="选择结束时间"
                :clearable="false"
                @change="calculateTimeDiff(row)"
              ></el-time-picker>
            </div>
            
            <!-- 检验员 -->
            <div class="form-item">
              <label class="form-label">检验员</label>
              <el-select
                v-model="row.inspectors"
                multiple
                placeholder="选择检验员"
              >
                <el-option
                  v-for="item in inspectorOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </div>
            
            <!-- 状态 -->
            <div class="form-item">
              <label class="form-label">状态</label>
              <el-select
                v-model="row.status"
                placeholder="选择状态"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </div>
            
            <!-- 数量 -->
            <div class="form-item">
              <label class="form-label">数量</label>
              <el-input
                v-model.number="row.quantity"
                type="number"
                placeholder="输入数量"
                min="0"
              ></el-input>
            </div>
            
            <!-- 总时间 -->
            <div class="form-item">
              <label class="form-label">总时长(小时)</label>
              <el-input
                v-model="row.totalTime"
                placeholder="自动计算"
                readonly
                :disabled="true"
              ></el-input>
            </div>
            
            <!-- 删除按钮 -->
            <div class="form-item form-item-btn">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeRow(index)"
                :disabled="formRows.length <= 1 || !hasPermission('Update')"
              >删除</el-button>
            </div>
          </div>
          
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="addRow"
            style="margin-top: 10px"
            v-if="hasPermission('Update')"
          >
            增加一行
          </el-button>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitForm" 
          v-if="hasPermission(currentEditId ? 'Update' : 'Add')"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 选择检验人员+时间范围的导出对话框 -->
    <el-dialog
      title="选择导出条件"
      v-model="selectInspectorVisible"
      width="500px"
      :before-close="handleSelectInspectorClose"
    >
      <div class="inspector-selection">
        <!-- 检验人员选择 -->
        <el-select
          v-model="selectedInspectors"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入检验人员姓名搜索并选择（可选）"
          :remote-method="remoteSearchInspectors"
          :loading="inspectorLoading"
          style="width: 100%; margin-bottom: 15px;"
        >
          <el-option
            v-for="inspector in filteredInspectorOptions"
            :key="inspector"
            :label="inspector"
            :value="inspector"
          ></el-option>
        </el-select>
        
        <!-- 新增：时间范围选择 -->
        <div class="time-range-selection" style="margin-bottom: 15px;">
          <div style="font-size: 14px; color: #666; margin-bottom: 8px;">时间范围筛选（可选）</div>
          <el-date-picker
            v-model="exportStartTime"
            type="date"
            placeholder="选择导出开始日期"
            style="width: 48%; margin-right: 4%;"
            :clearable="true"
          ></el-date-picker>
          <el-date-picker
            v-model="exportEndTime"
            type="date"
            placeholder="选择导出结束日期"
            style="width: 48%;"
            :clearable="true"
          ></el-date-picker>
          <p style="margin-top: 8px; font-size: 12px; color: #999;">
            提示：时间范围将筛选「时间段与该范围有交集」的记录（如选2023-07-01，会包含7月1日00:00-23:59的记录）
          </p>
        </div>
        
        <!-- 已选条件展示 -->
        <div class="selected-conditions" v-if="selectedInspectors.length > 0 || exportStartTime || exportEndTime">
          <div style="font-size: 14px; color: #666; margin-bottom: 5px;">已选筛选条件：</div>
          <div style="font-size: 13px; line-height: 1.5;">
            <span v-if="selectedInspectors.length > 0">检验人员：{{ selectedInspectors.join('、') }}</span>
            <span v-if="selectedInspectors.length > 0 && (exportStartTime || exportEndTime)"> | </span>
            <span v-if="exportStartTime || exportEndTime">
              时间范围：
              {{ exportStartTime ? formatDateForFileName(exportStartTime) : '不限' }}
              至
              {{ exportEndTime ? formatDateForFileName(exportEndTime) : '不限' }}
            </span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="selectInspectorVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmExport"
          :loading="exportLoading"
        >
          确认导出
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 导入Excel导出依赖
import XLSX from 'xlsx';
import FileSaver from 'file-saver';

export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      // 搜索相关
      searchKeyword: '',
      searchLoading: false,
      // 对话框状态
      dialogVisible: false,
      dialogTitle: '新建记录',
      currentEditId: null,
      // 权限控制
      PermissionAll: [],
      // 基本信息
      baseInfo: {
        workOrderNo: '',
        productCode: '',
        batchNo: '',
        productSpec: '',
        grade: '',
        coating: '',
        unitWeight: null,
        batchQuantity: null,
        qualifiedQuantity: null,
        batchWeight: null,
        packagingWeight: null
      },
      // 检验记录行
      formRows: [
        {
          startDate: null,
          startTime: null,
          endDate: null,
          endTime: null,
          inspectors: [],
          status: '',
          quantity: null,
          totalTime: ''
        }
      ],
      // 下拉选项
      inspectorOptions: ['张三', '李四', '王五', '赵六', '钱七', '孙八'],
      statusOptions: ['待处理', '处理中', '已完成', '已取消'],
      statusTagType: {
        '待处理': 'info',
        '处理中': 'warning',
        '已完成': 'success',
        '已取消': 'danger'
      },
      // 权限信息显示控制
      showPermissionInfo: true,
      // 导出相关 - 原有字段
      selectInspectorVisible: false,
      selectedInspectors: [],
      allInspectors: [],
      filteredInspectorOptions: [],
      inspectorLoading: false,
      // 导出相关 - 新增：时间范围字段
      exportStartTime: null, // 导出开始日期
      exportEndTime: null,   // 导出结束日期
      // 加载状态
      tableLoading: false,
      operationLoading: false,
      submitLoading: false,
      exportLoading: false
    };
  },
  
  computed: {
    // 过滤后的数据
    filteredData() {
      if (!this.searchKeyword) return this.tableData;
      
      const keyword = this.searchKeyword.toLowerCase().trim();
      return this.tableData.filter(item => {
        // 检查工单号、产品代码等基本信息
        const baseInfoMatch = item.workOrderNo?.toLowerCase().includes(keyword) ||
                             item.productCode?.toLowerCase().includes(keyword) ||
                             item.batchNo?.toLowerCase().includes(keyword) ||
                             item.productSpec?.toLowerCase().includes(keyword) ||
                             item.grade?.toLowerCase().includes(keyword) ||
                             item.coating?.toLowerCase().includes(keyword);
                             
        // 检查时间信息
        const timeMatch = item.startTime?.toLowerCase().includes(keyword) || 
                         item.endTime?.toLowerCase().includes(keyword);
                         
        // 检查检验员
        const inspectorMatch = item.inspectors?.some(ins => 
          ins.toLowerCase().includes(keyword)
        );
        
        // 检查状态和数量
        const statusMatch = item.status?.toLowerCase().includes(keyword);
        const quantityMatch = item.quantity?.toString().includes(keyword);
        const totalTimeMatch = item.totalTime?.toString().includes(keyword);
        
        return baseInfoMatch || timeMatch || inspectorMatch || statusMatch || quantityMatch || totalTimeMatch;
      });
    }
  },
  
  methods: {
    // 显示选择检验人员+时间范围的对话框
    showInspectorSelectDialog() {
      // 获取所有不重复的检验人员
      const inspectorsSet = new Set();
      this.tableData.forEach(item => {
        if (item.inspectors && Array.isArray(item.inspectors)) {
          item.inspectors.forEach(inspector => {
            inspectorsSet.add(inspector);
          });
        }
      });
      
      // 添加从选项中获取的检验人员
      this.inspectorOptions.forEach(inspector => {
        inspectorsSet.add(inspector);
      });
      
      this.allInspectors = Array.from(inspectorsSet).sort();
      this.filteredInspectorOptions = [...this.allInspectors];
      // 重置所有筛选条件
      this.selectedInspectors = [];
      this.exportStartTime = null;
      this.exportEndTime = null;
      this.selectInspectorVisible = true;
    },
    
    // 远程搜索检验人员
    remoteSearchInspectors(query) {
      if (query !== '') {
        this.inspectorLoading = true;
        // 模拟远程搜索延迟
        setTimeout(() => {
          this.filteredInspectorOptions = this.allInspectors.filter(inspector => {
            return inspector.toLowerCase().includes(query.toLowerCase());
          });
          this.inspectorLoading = false;
        }, 200);
      } else {
        this.filteredInspectorOptions = [...this.allInspectors];
        this.inspectorLoading = false;
      }
    },
    
    // 确认导出（新增时间范围过滤逻辑）
    async confirmExport() {
      // 1. 校验：至少选择一个筛选条件
      const hasInspector = this.selectedInspectors && this.selectedInspectors.length > 0;
      const hasTimeRange = this.exportStartTime || this.exportEndTime;
      if (!hasInspector && !hasTimeRange) {
        this.$message.warning('请至少选择一位检验人员或一个时间范围');
        return;
      }

      try {
        this.exportLoading = true;        
        // 2. 处理时间范围：转成时间戳（开始时间00:00:00，结束时间23:59:59）
        let timeFilterStart = null;
        let timeFilterEnd = null;
        if (this.exportStartTime) {
          timeFilterStart = new Date(this.exportStartTime);
          timeFilterStart.setHours(0, 0, 0, 0); // 当天开始
          timeFilterStart = timeFilterStart.getTime();
        }
        if (this.exportEndTime) {
          timeFilterEnd = new Date(this.exportEndTime);
          timeFilterEnd.setHours(23, 59, 59, 999); // 当天结束
          timeFilterEnd = timeFilterEnd.getTime();
        }

        // 3. 多条件过滤数据（检验人员 + 时间范围）
        const exportData = this.tableData.filter(item => {
          // 检验人员过滤：无选择则全部匹配
          const inspectorMatch = !hasInspector 
            ? true 
            : (item.inspectors && item.inspectors.some(ins => this.selectedInspectors.includes(ins)));
          
          // 时间范围过滤：无选择则全部匹配；有选择则判断交集
          let timeMatch = true;
          if (hasTimeRange) {
            // 转记录时间为时间戳
            const recordStart = item.startTime ? new Date(item.startTime).getTime() : null;
            const recordEnd = item.endTime ? new Date(item.endTime).getTime() : null;
            // 记录无时间信息则不匹配
            if (!recordStart || !recordEnd) {
              timeMatch = false;
            } else {
              // 交集判断逻辑：记录开始时间 <= 筛选结束时间 且 记录结束时间 >= 筛选开始时间
              if (timeFilterStart) timeMatch = timeMatch && recordEnd >= timeFilterStart;
              if (timeFilterEnd) timeMatch = timeMatch && recordStart <= timeFilterEnd;
            }
          }
          
          return inspectorMatch && timeMatch;
        });

        if (exportData.length === 0) {
          this.$message.info('未找到符合筛选条件的记录');
          this.selectInspectorVisible = false;
          return;
        }

        // 4. 整理导出数据格式
        const excelData = exportData.map(item => ({
          '工单号': item.workOrderNo || '',
          '产品代码': item.productCode || '',
          '批次号': item.batchNo || '',
          '开始时间': item.startTime || '',
          '结束时间': item.endTime || '',
          '检验员': item.inspectors?.join('、') || '',
          '状态': item.status || '',
          '数量': item.quantity || '',
          '总时长(小时)': item.totalTime || ''
        }));
        
        // 5. 计算合计行（总时长）
        const totalHours = exportData.reduce((sum, item) => {
          return sum + parseFloat(item.totalTime || 0);
        }, 0);
        excelData.push({
          '工单号': '合计',
          '产品代码': '',
          '批次号': '',
          '开始时间': '',
          '结束时间': '',
          '检验员': '',
          '状态': '',
          '数量': '',
          '总时长(小时)': totalHours.toFixed(2)
        });

        // 6. 生成Excel并导出（文件名包含筛选条件）
        const ws = XLSX.utils.json_to_sheet(excelData);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, `检验记录`);

        const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
        const excelBlob = new Blob([excelBuffer], { type: 'application/octet-stream' });
        
        // 生成包含筛选条件的文件名
        const fileNameParts = ['检验记录'];
        if (hasInspector) fileNameParts.push(`检验员${this.selectedInspectors.join('_')}`);
        if (hasTimeRange) {
          const startStr = this.exportStartTime ? this.formatDateForFileName(this.exportStartTime) : '不限';
          const endStr = this.exportEndTime ? this.formatDateForFileName(this.exportEndTime) : '不限';
          fileNameParts.push(`时间${startStr}_至_${endStr}`);
        }
        fileNameParts.push(this.formatDateForFileName(new Date()));
        const fileName = `${fileNameParts.join('_')}.xlsx`;
        
        FileSaver.saveAs(excelBlob, fileName);
        this.$message.success('导出成功');
        this.selectInspectorVisible = false;
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败，请重试');
      } finally {
        this.exportLoading = false;
      }
    },
    
    // 格式化日期为文件名格式（复用方法）
    formatDateForFileName(date) {
      return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())}`;
    },
    
    // 关闭导出对话框时重置筛选条件
    handleSelectInspectorClose() {
      this.selectInspectorVisible = false;
      this.selectedInspectors = [];
      this.exportStartTime = null;
      this.exportEndTime = null;
    },

    // 表格搜索处理
    handleSearch() {
      this.searchLoading = true;
      // 使用setTimeout模拟搜索延迟
      setTimeout(() => {
        this.searchLoading = false;
        // 若搜索无结果，给出提示
        if (this.filteredData.length === 0) {
          this.$message.info(`未找到包含"${this.searchKeyword}"的记录`);
        }
      }, 300);
    },

    // 刷新数据
    refreshData() {
      this.get_gx_detail_all();
    },

    // 获取工序和检验员数据
    get_gx_detail_all() {
      try {
        this.tableLoading = true;
        this.operationLoading = true;
        
        console.log("获取工序和检验员数据");
        this.inspectorOptions = [];
        this.statusOptions = [];
        
        // 实际项目确保this.http已挂载（axios）
        Promise.all([
          // 获取工序和检验员数据
          this.http.get('api/ak_wgjy_sgd_peizhi/search_gx_detail', {}),
          // 获取表格数据
          this.http.get('api/ak_wgjy_sgd_peizhi/search_info_db', {})
        ])
        .then(([gxRes, tableRes]) => {
          // 处理工序和检验员数据
          console.log("工序/检验员数据:", gxRes);
          if (gxRes.rows && Array.isArray(gxRes.rows)) {
            gxRes.rows.forEach(per_ => {
              if (per_.type === "工序") {
                this.statusOptions.push(per_.name);
              } else {
                this.inspectorOptions.push(per_.name);
              }
            });
          }
          
          // 处理表格数据
          console.log("表格数据:", tableRes);
          this.tableData = [];
          if (tableRes.rows && Array.isArray(tableRes.rows) && tableRes.rows.length > 0) {
            tableRes.rows.forEach((per_, index) => {
              per_.id = index + 1;
              per_.inspectors = per_.inspectors ? per_.inspectors.split(', ') : [];
              this.tableData.push(per_);
            });
          } else {
            // 无数据时使用默认测试数据
            this.$message.info('未获取到后端数据，使用测试数据');
            this.setTestData();
          }
          
          this.$message.success('数据加载成功');
        })
        .catch((error) => {
          console.error('数据加载失败:', error);
          this.$message.error('数据加载失败，使用本地测试数据');
          // 接口失败时恢复默认选项（确保功能可用）
          this.inspectorOptions = ['张三', '李四', '王五', '赵六', '钱七', '孙八'];
          this.statusOptions = ['待处理', '处理中', '已完成', '已取消'];
          this.setTestData();
        })
        .finally(() => {
          this.tableLoading = false;
          this.operationLoading = false;
        });
      } catch (error) {
        console.error('获取数据异常:', error);
        this.tableLoading = false;
        this.operationLoading = false;
        this.$message.error('获取数据异常，请重试');
      }
    },

    // 设置测试数据
    setTestData() {
      this.tableData = [
        {
          id: 1,
          workOrderNo: 'WO202307001',
          productCode: 'PC001',
          batchNo: 'B202307001',
          productSpec: 'Φ10×20mm',
          grade: '304',
          coating: 'Zn',
          unitWeight: 0.5,
          batchQuantity: 1000,
          qualifiedQuantity: 980,
          batchWeight: 500,
          packagingWeight: 50,
          startTime: '2023-07-01 08:00',
          endTime: '2023-07-01 12:00',
          inspectors: ['张三', '李四'],
          status: '已完成',
          quantity: 25,
          totalTime: '4.00'
        },
        {
          id: 2,
          workOrderNo: 'WO202307002',
          productCode: 'PC002',
          batchNo: 'B202307002',
          productSpec: 'Φ12×25mm',
          grade: '316',
          coating: 'Ni',
          unitWeight: 0.8,
          batchQuantity: 800,
          qualifiedQuantity: 790,
          batchWeight: 640,
          packagingWeight: 60,
          startTime: '2023-07-01 13:00',
          endTime: '2023-07-01 17:00',
          inspectors: ['王五'],
          status: '待处理',
          quantity: 18,
          totalTime: '4.00'
        },
        {
          id: 3,
          workOrderNo: 'WO202307003',
          productCode: 'PC003',
          batchNo: 'B202307003',
          productSpec: 'Φ8×15mm',
          grade: '304',
          coating: 'Zn',
          unitWeight: 0.3,
          batchQuantity: 1500,
          qualifiedQuantity: 1480,
          batchWeight: 450,
          packagingWeight: 40,
          startTime: '2023-07-02 09:00',
          endTime: '2023-07-02 11:30',
          inspectors: ['张三'],
          status: '已完成',
          quantity: 30,
          totalTime: '2.50'
        },
        {
          id: 4,
          workOrderNo: 'WO202307004',
          productCode: 'PC004',
          batchNo: 'B202307004',
          productSpec: 'Φ15×30mm',
          grade: '316L',
          coating: 'Cr',
          unitWeight: 1.2,
          batchQuantity: 500,
          qualifiedQuantity: 495,
          batchWeight: 600,
          packagingWeight: 30,
          startTime: '2023-07-03 14:00',
          endTime: '2023-07-03 16:30',
          inspectors: ['赵六', '李四'],
          status: '处理中',
          quantity: 15,
          totalTime: '2.50'
        }
      ];
    },

    // 工单号回车事件，同步生产任务
    handleWorkOrderEnter() {
      if (!this.baseInfo.workOrderNo) return;
      
      this.$message.info('检测到工单号回车，同步生产任务');
      this.operationLoading = true;
      
      this.http.get('api/table_wgjy/SyncProductionTask_wgjy_get', {
        name_order: this.baseInfo.workOrderNo
      })
        .then((reslut) => {
          console.log("生产任务数据:", reslut);
          const task = reslut.rows && reslut.rows.length > 0 ? reslut.rows[0] : {};
          this.baseInfo.productCode = task.product || '';
          this.baseInfo.batchNo = task.raw_lot_id || '';
          this.baseInfo.productSpec = task.prodcut_spec || '';
          this.baseInfo.grade = task.grade || '';
          this.baseInfo.unitWeight = task.piece_weight || null;
          this.$message.success('生产任务同步成功');
        })
        .catch((error) => {
          console.error('同步生产任务失败:', error);
          this.$message.error('同步生产任务失败，请手动输入产品信息');
        })
        .finally(() => {
          this.operationLoading = false;
        });
    },

    // 权限检查核心方法
    hasPermission(permission) {
      if (!Array.isArray(this.PermissionAll)) return false;
      return this.PermissionAll.includes(permission);
    },

    // 打开新建对话框
    openCreateDialog() {
      if (!this.hasPermission('Add')) {
        this.$message.error('您没有新建权限，请联系管理员');
        return;
      }
      this.dialogTitle = '新建记录';
      this.currentEditId = null;
      this.resetFormData();
      this.$nextTick(() => {
        this.dialogVisible = true;
      });
    },

    // 打开编辑对话框
    openEditDialog(row) {
      if (!this.hasPermission('Update')) {
        this.$message.error('您没有编辑权限，请联系管理员');
        return;
      }
      this.dialogTitle = '编辑记录';
      this.currentEditId = row.id;
      this.resetFormData();

      // 填充基本信息
      this.baseInfo = {
        workOrderNo: row.workOrderNo || '',
        productCode: row.productCode || '',
        batchNo: row.batchNo || '',
        productSpec: row.productSpec || '',
        grade: row.grade || '',
        coating: row.coating || '',
        unitWeight: row.unitWeight || null,
        batchQuantity: row.batchQuantity || null,
        qualifiedQuantity: row.qualifiedQuantity || null,
        batchWeight: row.batchWeight || null,
        packagingWeight: row.packagingWeight || null
      };

      // 解析时间为日期和时间组件
      const startDateTime = row.startTime ? new Date(row.startTime) : new Date();
      const endDateTime = row.endTime ? new Date(row.endTime) : new Date();
      
      this.formRows[0] = {
        startDate: new Date(startDateTime.getFullYear(), startDateTime.getMonth(), startDateTime.getDate()),
        startTime: new Date(startDateTime),
        endDate: new Date(endDateTime.getFullYear(), endDateTime.getMonth(), endDateTime.getDate()),
        endTime: new Date(endDateTime),
        inspectors: [...(row.inspectors || [])],
        status: row.status || '',
        quantity: row.quantity || null,
        totalTime: row.totalTime || ''
      };

      this.$nextTick(() => {
        this.calculateTimeDiff(this.formRows[0]);
        this.dialogVisible = true;
      });
    },

    // 重置表单数据
    resetFormData() {
      // 重置基本信息
      this.baseInfo = {
        workOrderNo: '',
        productCode: '',
        batchNo: '',
        productSpec: '',
        grade: '',
        coating: '',
        unitWeight: null,
        batchQuantity: null,
        qualifiedQuantity: null,
        batchWeight: null,
        packagingWeight: null
      };

      // 重置检验记录（默认当天日期和时间）
      const today = new Date();
      const defaultDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
      
      this.formRows = [
        {
          startDate: defaultDate,
          startTime: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 8, 0, 0),
          endDate: defaultDate,
          endTime: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 12, 0, 0),
          inspectors: [],
          status: '',
          quantity: null,
          totalTime: ''
        }
      ];

      // 计算初始总时间
      this.$nextTick(() => {
        this.calculateTimeDiff(this.formRows[0]);
      });
    },

    // 添加一行检验记录
    addRow() {
      if (!this.hasPermission('Update')) {
        this.$message.error('您没有编辑权限，无法添加行');
        return;
      }
      
      const today = new Date();
      const defaultDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
      
      const newRow = {
        startDate: defaultDate,
        startTime: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 8, 0, 0),
        endDate: defaultDate,
        endTime: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 12, 0, 0),
        inspectors: [],
        status: '',
        quantity: null,
        totalTime: ''
      };
      
      this.formRows.push(newRow);
      this.$nextTick(() => {
        this.calculateTimeDiff(newRow);
      });
    },

    // 删除一行检验记录
    removeRow(index) {
      if (!this.hasPermission('Update')) {
        this.$message.error('您没有编辑权限，无法删除行');
        return;
      }
      
      if (this.formRows.length <= 1) {
        this.$message.warning('至少保留一行检验记录');
        return;
      }
      
      this.formRows.splice(index, 1);
    },

    // 删除记录
    handleDelete(id) {
      if (!this.hasPermission('Delete')) {
        this.$message.error('您没有删除权限，请联系管理员');
        return;
      }
      
      this.$confirm('确定要删除这条记录吗？删除后不可恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.operationLoading = true;
          
          // 实际项目需调用后端删除接口
          // 这里使用setTimeout模拟接口请求
          setTimeout(() => {
            this.tableData = this.tableData.filter(item => item.id !== id);
            this.$message.success('删除成功');
            this.operationLoading = false;
          }, 500);
        })
        .catch(() => {
          this.$message.info('已取消删除');
        });
    },

    // 提交表单
    submitForm() {
      // 权限校验
      const requiredPerm = this.currentEditId ? 'Update' : 'Add';
      if (!this.hasPermission(requiredPerm)) {
        this.$message.error(`您没有${this.currentEditId ? '编辑' : '新建'}权限，请联系管理员`);
        return;
      }

      if (!this.validateForm()) {
        return;
      }

      this.submitLoading = true;
      
      try {
        if (this.currentEditId) {
          // 编辑操作
          const index = this.tableData.findIndex(item => item.id === this.currentEditId);
          if (index !== -1) {
            const row = this.formRows[0];
            this.tableData[index] = {
              ...this.tableData[index],
              ...this.baseInfo,
              startTime: this.formatDateTime(row.startDate, row.startTime),
              endTime: this.formatDateTime(row.endDate, row.endTime),
              inspectors: row.inspectors,
              status: row.status,
              quantity: row.quantity,
              totalTime: row.totalTime
            };
            
            // 调用后端更新接口
            this.updateWorkOrder([this.tableData[index]], "更新")
              .then(() => {
                this.$message.success('编辑成功');
                this.dialogVisible = false;
              })
              .finally(() => {
                this.submitLoading = false;
              });
          }
        } else {
          // 新建操作
          const inBefore = this.tableData.length;
          this.formRows.forEach(row => {
            const newId = Math.max(...this.tableData.map(item => item.id || 0), 0) + 1;
            const newRecord = {
              id: newId,
              ...this.baseInfo,
              startTime: this.formatDateTime(row.startDate, row.startTime),
              endTime: this.formatDateTime(row.endDate, row.endTime),
              inspectors: row.inspectors,
              status: row.status,
              quantity: row.quantity,
              totalTime: row.totalTime
            };
            this.tableData.push(newRecord);
          });
          
          const inAfter = this.tableData.length;
          const newRecords = this.tableData.slice(inBefore, inAfter);
          
          // 调用后端创建接口
          this.updateWorkOrder(newRecords, "创建")
            .then(() => {
              this.$message.success('创建成功');
              this.dialogVisible = false;
            })
            .finally(() => {
              this.submitLoading = false;
            });
        }
      } catch (error) {
        console.error('提交表单失败:', error);
        this.$message.error('提交失败，请重试');
        this.submitLoading = false;
      }
    },

    // 更新工单到后端
    updateWorkOrder(workOrder, option) {
      return new Promise((resolve, reject) => {
        try {
          console.log(`${option}工单数据:`, workOrder);
          const jsonStringMesData = JSON.stringify(workOrder);

          this.http.get('api/ak_wgjy_sgd_peizhi/insert_info_gx', {
            option: option,
            mes_data: jsonStringMesData
          })
            .then((reslut) => {
              if (reslut === "成功") {
                resolve();
              } else {
                this.$message.warning(`工单${option}返回异常: ${reslut}`);
                reject(new Error(`工单${option}返回异常`));
              }
            })
            .catch((error) => {
              console.error(`${option}工单失败:`, error);
              this.$message.error(`工单${option}失败，请重试`);
              reject(error);
            });
        } catch (error) {
          console.error(`${option}工单异常:`, error);
          this.$message.error(`工单${option}失败，请稍后重试`);
          reject(error);
        }
      });
    },

    // 表单验证
    validateForm() {
      // 验证基本信息
      if (!this.baseInfo.workOrderNo) {
        this.$message.error('请输入工单号');
        return false;
      }
      
      if (!this.baseInfo.productCode) {
        this.$message.error('请输入产品代码');
        return false;
      }
      
      if (!this.baseInfo.batchNo) {
        this.$message.error('请输入批次号');
        return false;
      }

      // 验证检验记录
      for (let i = 0; i < this.formRows.length; i++) {
        const row = this.formRows[i];
        
        if (!row.startDate) {
          this.$message.error(`第${i+1}行检验记录：请选择开始日期`);
          return false;
        }
        
        if (!row.startTime) {
          this.$message.error(`第${i+1}行检验记录：请选择开始时间`);
          return false;
        }
        
        if (!row.endDate) {
          this.$message.error(`第${i+1}行检验记录：请选择结束日期`);
          return false;
        }
        
        if (!row.endTime) {
          this.$message.error(`第${i+1}行检验记录：请选择结束时间`);
          return false;
        }
        
        if (!row.inspectors || row.inspectors.length === 0) {
          this.$message.error(`第${i+1}行检验记录：请选择检验员`);
          return false;
        }
        
        if (!row.status) {
          this.$message.error(`第${i+1}行检验记录：请选择状态`);
          return false;
        }
        
        if (row.quantity === null || row.quantity < 0) {
          this.$message.error(`第${i+1}行检验记录：请输入有效的数量`);
          return false;
        }
        
        if (!row.totalTime || isNaN(parseFloat(row.totalTime)) || parseFloat(row.totalTime) <= 0) {
          this.$message.error(`第${i+1}行检验记录：时间范围异常，请重新选择`);
          return false;
        }
      }
      
      return true;
    },

    // 关闭对话框
    handleDialogClose() {
      this.resetFormData();
      this.dialogVisible = false;
    },

    // 格式化日期时间
    formatDateTime(date, time) {
      if (!(date instanceof Date) || !(time instanceof Date)) return '';
      
      const year = date.getFullYear();
      const month = this.padZero(date.getMonth() + 1);
      const day = this.padZero(date.getDate());
      const hours = this.padZero(time.getHours());
      const minutes = this.padZero(time.getMinutes());
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 数字补零
    padZero(num) {
      return num < 10 ? `0${num}` : num;
    },

    // 计算时间差
    calculateTimeDiff(row) {
      try {
        if (!(row.startDate instanceof Date) || !(row.startTime instanceof Date) ||
            !(row.endDate instanceof Date) || !(row.endTime instanceof Date)) {
          row.totalTime = '';
          return;
        }

        // 组合完整时间
        const startTime = new Date(
          row.startDate.getFullYear(),
          row.startDate.getMonth(),
          row.startDate.getDate(),
          row.startTime.getHours(),
          row.startTime.getMinutes()
        );
        
        const endTime = new Date(
          row.endDate.getFullYear(),
          row.endDate.getMonth(),
          row.endDate.getDate(),
          row.endTime.getHours(),
          row.endTime.getMinutes()
        );

        if (startTime > endTime) {
          this.$message.warning('开始时间不能晚于结束时间');
          row.totalTime = '';
          return;
        }

        // 计算小时差（保留2位小数）
        const diffMs = endTime - startTime;
        const diffHours = (diffMs / 3600000).toFixed(2);
        row.totalTime = diffHours;
      } catch (error) {
        console.error('计算时间差失败:', error);
        row.totalTime = '';
      }
    }
  },
  
  created() {
    // 1. 获取权限（从store）
    const permissionData = this.$store.getters.getPermission('/suigd') || {};
    this.PermissionAll = permissionData.permission || [];
    console.log("当前用户权限:", this.PermissionAll);

    // 2. 获取用户信息（可选）
    console.log("当前用户信息:", this.$store.getters.getUserInfo() || '未获取到');

    // 3. 初始化数据
    this.get_gx_detail_all();
    console.log("初始化完成");

    // 4. 容错：默认权限（开发环境用，生产环境移除）
    if (this.PermissionAll.length === 0) {
      console.log("未获取到权限，使用默认权限（开发环境）");
      this.PermissionAll = ['Add', 'Update', 'Delete', 'Export'];
    }
  }
};
</script>

<style scoped>
.inspection-form-container {
  padding: 20px;
  background-color: #fff;
  min-height: 500px;
}

.operation-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.dialog-content {
  max-height: 600px;
  overflow-y: auto;
  padding-right: 10px;
}

.dialog-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.dialog-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.section-title {
  margin-bottom: 15px;
  color: #333;
  font-size: 16px;
  font-weight: 500;
  padding-left: 5px;
  border-left: 3px solid #42b983;
}

.form-group {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
  gap: 10px;
}

.form-item {
  display: flex;
  flex-direction: column;
  width: 10%;
  box-sizing: border-box;
}

/* 调整第二行基本信息的宽度 */
.form-group:nth-child(2) .form-item {
  width: 10%;
}

.form-label {
  font-size: 13px;
  color: #666;
  margin-bottom: 5px;
  padding-left: 5px;
}

.form-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #e5e5e5;
  flex-wrap: wrap;
  gap: 10px;
}

.form-row:last-child {
  border-bottom: none;
}

/* 时间相关输入项宽度调整 */
.form-item-time {
  width: 12%;
}

/* 按钮项宽度调整 */
.form-item-btn {
  width: 5%;
  padding-top: 24px; /* 与标签高度对齐 */
}

.permission-info {
  margin-left: auto;
  color: #666;
  font-size: 12px;
  padding: 5px 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.permission-enabled {
  color: #42b983;
  font-weight: bold;
}

.el-input[readonly] {
  background-color: #f5f7fa;
  color: #666;
}

/* 导出按钮样式协调 */
.el-button--info {
  margin-left: 10px;
}

/* 检验人员选择对话框样式 */
.inspector-selection {
  margin-top: 10px;
}

/* 已选择检验人员显示样式 */
.selected-conditions {
  margin-top: 10px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  color: #666;
}

/* 响应式调整 */
@media screen and (max-width: 1400px) {
  .form-item {
    width: 24%;
    margin-bottom: 10px;
  }
  
  .form-group:nth-child(2) .form-item {
    width: 32%;
  }
  
  .form-item-time {
    width: 23%;
  }
}

@media screen and (max-width: 992px) {
  .form-item {
    width: 32%;
  }
  
  .form-group:nth-child(2) .form-item {
    width: 48%;
  }
  
  .form-item-time {
    width: 48%;
  }
  
  .form-item-btn {
    width: 100%;
    padding-top: 0;
    margin-top: 10px;
  }
  
  /* 导出对话框时间选择器响应式 */
  .time-range-selection .el-date-picker {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 8px;
  }
}
</style>